package com.heima.schedule.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.common.constants.RedisConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.utils.common.BeanHelper;
import com.heima.utils.common.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 同步DB至Redis
 */
@Component
@Slf4j
public class SyncDbToCacheJob {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 定时任务
     */
    @Scheduled(fixedRate = 10000)
    public void syncData(){
        log.info("任务被触发了,{}",new Date());

        //获取所有5分钟后到期任务
        Date futureDate = DateTime.now().plusMinutes(5).toDate();
        QueryWrapper<Taskinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("execute_time",futureDate);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(queryWrapper);

        //定时同步数据到Redis
        if (CollectionUtils.isNotEmpty(taskinfos)){
            for (Taskinfo taskinfo : taskinfos) {
                String key = RedisConstants.TASK_TOPIC_PREFIX+taskinfo.getTaskTopic();
                Task task = BeanHelper.copyProperties(taskinfo,Task.class);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                redisTemplate.opsForZSet().add(key, JsonUtils.toString(task),task.getExecuteTime());
            }
        }



    }
}
